package com.liujit.standard.basis.core.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.StrUtil;

/**
 * @description: XSS过滤器
 * @author: liujun
 * @create: 2021/3/28 5:21 下午
 **/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(filterName = "XssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //点击劫持：X-Frame-Options未配置  漏洞修改
        resp.addHeader("x-frame-options","SAMEORIGIN");
        if (req.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(req, resp);
        }else if(StrUtil.isNotBlank(req.getHeader("Content-Type")) && req.getHeader("Content-Type").startsWith("multipart/form-data;")) {
            filterChain.doFilter(req, resp);
        } else {
            filterChain.doFilter(new XssRequestWrapper(req), resp);
        }
    }
}
